package org.jeecg.modules.checkInventory.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.Inventory.entity.Inventory;
import org.jeecg.modules.Inventory.service.IInventoryService;
import org.jeecg.modules.checkInventory.entity.CheckInventory;
import org.jeecg.modules.checkInventory.service.ICheckInventoryService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.dataLog.entity.DataLog;
import org.jeecg.modules.dataLog.service.IDataLogService;
import org.jeecg.modules.operationLog.entity.OperationLog;
import org.jeecg.modules.operationLog.service.IOperationLogService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 盘点表
 * @Author: jeecg-boot
 * @Date:   2024-06-27
 * @Version: V1.0
 */
@Api(tags="盘点表")
@RestController
@RequestMapping("/checkInventory/checkInventory")
@Slf4j
public class CheckInventoryController extends JeecgController<CheckInventory, ICheckInventoryService> {
	@Autowired
	private ICheckInventoryService checkInventoryService;
	@Autowired
	private IInventoryService inventoryService;
	@Autowired
	private IOperationLogService operationLogService;
	 @Autowired
	 private IDataLogService dataLogService;
	
	/**
	 * 分页列表查询
	 *
	 * @param checkInventory
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "盘点表-分页列表查询")
	@ApiOperation(value="盘点表-分页列表查询", notes="盘点表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(CheckInventory checkInventory,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CheckInventory> queryWrapper = QueryGenerator.initQueryWrapper(checkInventory, req.getParameterMap());
		Page<CheckInventory> page = new Page<CheckInventory>(pageNo, pageSize);
		IPage<CheckInventory> pageList = checkInventoryService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@PostMapping("/handleCheck")
	public Result<?> handleCheck(@RequestBody CheckInventory checkInventory) {
		int number = checkInventory.getNumber();
		int checkNumber = checkInventory.getCheckNumber();
		int differentNumber = checkNumber - number;
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		checkInventory.setDifferentNumber(differentNumber)
				.setCheckMan(user.getRealname()).setCheckTime(new Date());
		if (differentNumber == 0) {
			checkInventory.setResult(0);
			checkInventory.setStatus(4);
		} else if (differentNumber < 0) {
			checkInventory.setResult(-1);
			checkInventory.setStatus(2);
		} else {
			checkInventory.setResult(1);
			checkInventory.setStatus(2);
		}
		OperationLog operationLog = new OperationLog();
		operationLog.setSkuCode(checkInventory.getSkuCode()).setOperationTime(new Date())
				.setOperationType("盘点操作").setOperator(user.getRealname())
				.setLocation(checkInventory.getLocation());
		checkInventoryService.updateById(checkInventory);
		operationLogService.save(operationLog);
		return Result.OK("盘点成功", null);
	}

	@PostMapping("/sycn")
	public Result<?> sycn(@RequestBody CheckInventory checkInventory) {
		CheckInventory byId = checkInventoryService.getById(checkInventory.getId());
		if (byId == null) {
			return Result.error("未找到对应数据");
		}
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		OperationLog operationLog = new OperationLog();
		operationLog.setSkuCode(checkInventory.getSkuCode()).setOperationTime(new Date())
				.setOperationType("处理盘点差异").setOperator(user.getRealname())
				.setLocation(checkInventory.getLocation());
		checkInventory.setStatus(3);
		checkInventoryService.updateById(checkInventory);
		operationLogService.save(operationLog);
		return Result.OK("差异处理成功", null);
	}
	
	/**
	 *   添加
	 *
	 * @param checkInventory
	 * @return
	 */
	@AutoLog(value = "盘点表-添加")
	@ApiOperation(value="盘点表-添加", notes="盘点表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody CheckInventory checkInventory) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		DataLog dataLog = new DataLog();
		dataLog.setOperator(user.getRealname()).setOperationTime(new Date())
				.setOperationType("新增").setOperationClass("盘点表")
				.setUpdated(checkInventory.toString());
		checkInventoryService.save(checkInventory);
		dataLogService.save(dataLog);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param checkInventory
	 * @return
	 */
	@AutoLog(value = "盘点表-编辑")
	@ApiOperation(value="盘点表-编辑", notes="盘点表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody CheckInventory checkInventory) {
		CheckInventory byId = checkInventoryService.getById(checkInventory.getId());
		if (byId == null) {
			return Result.error("未找到对应数据");
		}
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		DataLog dataLog = new DataLog();
		dataLog.setOperator(user.getRealname()).setOperationTime(new Date())
				.setOperationType("编辑").setOperationClass("盘点表")
				.setOriginal(byId.toString()).setUpdated(checkInventory.toString());
		checkInventoryService.updateById(checkInventory);
		dataLogService.save(dataLog);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "盘点表-通过id删除")
	@ApiOperation(value="盘点表-通过id删除", notes="盘点表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		CheckInventory byId = checkInventoryService.getById(id);
		if (byId == null) {
			return Result.error("未找到对应数据");
		}
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		DataLog dataLog = new DataLog();
		dataLog.setOperator(user.getRealname()).setOperationTime(new Date())
				.setOperationType("删除").setOperationClass("盘点表")
				.setOriginal(byId.toString());
		checkInventoryService.removeById(id);
		dataLogService.save(dataLog);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "盘点表-批量删除")
	@ApiOperation(value="盘点表-批量删除", notes="盘点表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> list = Arrays.asList(ids.split(","));
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		Date date = new Date();
		List<DataLog> dataLogs = new ArrayList<>();
		for (CheckInventory checkInventory : checkInventoryService.listByIds(list)) {
			DataLog dataLog = new DataLog();
			dataLog.setOperator(user.getRealname()).setOperationTime(date)
					.setOperationType("删除").setOperationClass("库存表")
					.setOriginal(checkInventory.toString());
			dataLogs.add(dataLog);
		}
		this.checkInventoryService.removeByIds(list);
		dataLogService.saveBatch(dataLogs);
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "盘点表-通过id查询")
	@ApiOperation(value="盘点表-通过id查询", notes="盘点表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		CheckInventory checkInventory = checkInventoryService.getById(id);
		if(checkInventory==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(checkInventory);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param checkInventory
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CheckInventory checkInventory) {
        return super.exportXls(request, checkInventory, CheckInventory.class, "盘点表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CheckInventory.class);
    }

}
